package com.egoonet.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.egoonet.util.ParamUtils;
import com.egoonet.websocket.WebSocketServer;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;

/**
 * 该接口用于向所有在线用户发送消息
 * @author wchi
 *
 */
@WebServlet("/broadcast")
public class BrocadcastServlet extends HttpServlet {
	Logger logger = LoggerFactory.getLogger(BrocadcastServlet.class);
	private static final long serialVersionUID = 1L;
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String sendid = ParamUtils.getParameter(request, "sendid");
		String msgbody = ParamUtils.getParameter(request, "msgbody");
		
		Boolean isSuccess = false;
		String msg = " ";
		
		logger.debug("接收到消息广播请求，sendid[{}], msgbody[{}]", sendid, msgbody);
		
		try {
			Preconditions.checkArgument(!Strings.isNullOrEmpty(msgbody), "null msgbdoy");
			isSuccess =WebSocketServer.broadcast(sendid, msgbody);
		} catch (Exception ex) {
			logger.warn("广播消息发送失败，因",  ex);
			msg = ex.getMessage();
		}
		
		JSONObject obj = new JSONObject();
		obj.put("result", isSuccess);
		obj.put("msg", msg);
		logger.debug("广播消息结果[{}]", obj);
		
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.getWriter().write(obj.toString());
		response.getWriter().flush();
		response.getWriter().close();
	}
}
